package models.merchant;

import com.sun.org.apache.xpath.internal.operations.Bool;
import helper.CacheCallBack;
import helper.CacheHelper;
import models.BaseModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.merchant.enums.MerchantType;
import models.merchant.enums.VisitorType;
import models.weixin.WebUser;
import models.weixin.WeixinData;
import org.hibernate.impl.QueryImpl;
import org.hibernate.transform.Transformers;
import play.Logger;
import play.db.jpa.JPA;
import utils.ObjectUtil;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * Created by buhaoba on 16/6/16.
 */
@Entity
@Table(name = "power_merchants")
public class Merchant extends BaseModel {

    public static final String CACHE_MERCHANT_LINKId = "ULC_CACHE_MERCHANT_LINKID_";


    /**
     * 商户负责人 以后结算佣金等 都用该用户
     */
    @JoinColumn(name = "person_user_id")
    @ManyToOne
    public WebUser personUser;

    /**
     * 商户绑定的是哪个微信信息
     */
    @JoinColumn(name = "weixin_datas_id")
    @ManyToOne
    public WeixinData weixinData;

    /**
     * 商户链接编号
     */
    @Column(name = "link_id")
    public String linkId;

    /**
     * 商户设置
     */
    @JoinColumn(name = "set_up")
    @ManyToOne
    public SetUp setUp;

    /**
     * 名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 商户类型
     */
    @Column(name = "type")
    @Enumerated(EnumType.STRING)
    public MerchantType type;

    /**
     * 最低购买金额
     */
    @Column(name = "min_amount")
    public Float minAmount;

    /**
     * 免运费金额
     */
    @Column(name = "free_freight_amount")
    public Float freeFreightAmount;

    /**
     * 是否需要注册
     */
    @Column(name = "need_register")
    public Boolean needRegister;

    /**
     * 访问是否需要授权
     */
    @Column(name = "visit_auth")
    public Boolean visitAuth = Boolean.FALSE;
    /**
     * 是否显示优惠券
     */
    @Column(name="display_coupon")
    public Boolean displayCoupon=Boolean.TRUE;

    /**
     * 是否可用优惠券
     */
    @Column(name="play_coupon")
    public Boolean playCoupon=Boolean.TRUE;

    /**
     * 是否有分享用户 下单后 可获得红包
     */
    @Column(name = "have_share_redbao")
    public Boolean haveShareRedBao = Boolean.FALSE;


    /**
     * 红包金额
     */
    @Column(name = "red_bao_amount")
    public Double redBaoAmount = 1d;

    /**
     * 首页分享朋友圈/微信好友
     */
    @Column(name = "index_share")
    public Boolean indexShare = Boolean.FALSE;

    /**
     * 分享到朋友圈里面的标题
     */
    @Column(name = "share_title")
    public String shareTitle;


    /**
     * 提醒红包
     */
    @Column(name = "index_remind_coupon")
    public Boolean indexRemindCoupon = Boolean.FALSE;


    /**
     * 是否发放赠品
     */
    @Column(name = "offering_freebies")
    public Boolean offeringFreebies = Boolean.FALSE;


    /**
     * 关联的赠送代金券的ID
     */
    @Column(name = "discount_oupon_id")
    public Long discountCouponId;

    /**
     * 客服电话
     */
    @Column(name = "service_phone")
    public String servicePhone;

    /**
     * 商户地址
     */
    @Column(name = "merchant_address")
    public String merchantAddress;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 判断是否有访问权限
     *
     * @return
     */
    public Boolean canVisitor(WebUser wxUser) {
        SetUp setUp = this.setUp;
        // 验证访问者 必须有手机号码
        if (setUp.visitorPhone) {
            if (wxUser == null) {
                return false;
            }
            if (!ObjectUtil.checkNotBlock(wxUser.phone)) {
                return false;
            }
        }

        if (setUp.visitorType != null && setUp.visitorType != VisitorType.WHOLE) {
            if (wxUser == null) {
                return false;
            }
            // 如果设置为商户类型  访问者 只有为一个商户负责人 才能访问
            if (setUp.visitorType == VisitorType.MERCHANT) {
                if (!Merchant.checkByPerson(wxUser)) {
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 跟据LinkId 查询商户信息
     * 因为访问量巨大 所以首先从 Cache中获取
     * 如果获取不到再查询数据库
     *
     * @param linkId
     * @return
     */
    public static Merchant findByLinkId(final String linkId) {
        return Merchant.find("deleted = ? and linkId = ?", DeletedStatus.UN_DELETED, linkId).first();
//        return CacheHelper.getCache(CACHE_MERCHANT_LINKId + linkId, new CacheCallBack<Merchant>() {
//            @Override
//            public Merchant loadData() {
//                Logger.info("Log100991 findByLinkId linkId : %s", linkId);
//                return Merchant.find("deleted = ? and linkId = ?", DeletedStatus.UN_DELETED, linkId).first();
//            }
//        });
    }

    /**
     * 校验模版是否被使用
     *
     * @param id
     * @return
     */
    public static Boolean checkSetUpIsUsed(long id) {
        return Merchant.count("setUp.id=? and deleted=?", id, DeletedStatus.UN_DELETED) > 0;
    }


    /**
     * 校验公众号是否被使用
     *
     * @param id
     * @return
     */
    public static Boolean checkWeixinDataIsUsed(long id) {
        return Merchant.count("weixinData.id=? and deleted=?", id, DeletedStatus.UN_DELETED) > 0;
    }

    public static Boolean checkByPerson(WebUser weixinUser) {
        return Merchant.count("personUser = ? and delted = ?", weixinUser, DeletedStatus.UN_DELETED) > 0 ? true : false;
    }


    public static List<Merchant> findBySetUp(Long setUpId) {
        return Merchant.find("deleted = ? and setUp.id = ?", DeletedStatus.UN_DELETED, setUpId).fetch();
    }

    public static Long countBySetUp(Long setUpId) {
        return Merchant.count("deleted = ? and setUp.id = ?", DeletedStatus.UN_DELETED, setUpId);
    }

    /**
     * 加载所有商户信息
     *
     * @return
     */
    public static List<Merchant> loadAllMerchat() {
        return Merchant.find("deleted=?", DeletedStatus.UN_DELETED).fetch();
    }
    /**
     * 根据用户数据权限, 查询用户可以看到的商户数据
     * @param adminUser
     * @return
     */
    public static List<Merchant> loadMerchants(AdminUser adminUser){
        return Merchant.find(" deleted=? and id in (select AUM.merchant.id from AdminUserMerchant AUM where AUM.adminUser.id = " + adminUser.getId() + ")",DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 查询所有商户用于生成下拉框
     */
    public static List<Map<String, Object>> loadMerchantsForComoBox() {
        StringBuilder hql = new StringBuilder("select t.id as id ,t.name as name from Merchant t where t.deleted = '0' order by id desc");
        Query query = JPA.em().createQuery(hql.toString());
        query.unwrap(QueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> resultlist = query.getResultList();
        return resultlist;
    }

    public static Merchant findByLinkIdUnCache(String linkId) {
        return Merchant.find("linkId = ?" , linkId).first();
    }


    public static List<Merchant> findBySetUp(SetUp setUp) {
        return Merchant.find("setUp = ?" , setUp).fetch();
    }

    /**
     * 获取所有权限范围内的可用商户
     *
     * @return
     */
    public static List<Merchant> findAllAuthMerchant() {
        return Merchant.find("deleted = ?", DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据Id查询商户
     */
    public static Merchant findByMerchantId(long id) {
        return Merchant.find("id=? and deleted=?", id, DeletedStatus.UN_DELETED).first();
    }

    public static List<Merchant> loadByVisitAuth(){
        return Merchant.find(" deleted = ? and visitAuth = 1" , DeletedStatus.UN_DELETED).fetch();
    }
}
